package com.fanghuyun.iswaf.function;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;

import com.fanghuyun.iswaf.common.ClientLogger;
import com.fanghuyun.iswaf.common.Constants;
import com.fanghuyun.iswaf.filter.DoFilter;

public class Upload extends DoFilter{
	
	private static Logger logger = Logger.getLogger("iswaf");
	
	public static boolean checkSuffix(List<String> ls,Properties properties){
		try {
			String[] suffix = properties.getProperty("function.upload.not_allow_suffix").split(",");
			for(String str:ls){
				String s = str.substring(str.lastIndexOf(".")+1,str.length());
				for (int i = 0; i < suffix.length; i++) {
					if(suffix[i].equals(s.toLowerCase())||Pattern.compile("\\p{Cntrl}",Pattern.CASE_INSENSITIVE).matcher(suffix[i]).find()){
						return true;
					}
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return false;
	}
	
	public static Map<String,Object> getFormData(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String, Object>();
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(request);
			List<Map<String,Object>> fieldList = new ArrayList<Map<String,Object>>();
			List<String> fileList = new ArrayList<String>();
			Map<String,Object> field = null;
			while (iter.hasNext()) {
			    FileItemStream item = iter.next();
			    String name = item.getFieldName();
			    InputStream stream = item.openStream();
			    if (item.isFormField()) {
			    	field = new HashMap<String, Object>();
			    	field.put(name, Streams.asString(stream));
			    	field.put("type", "field");//form field
			    	fieldList.add(field);
			    } else {
			    	fileList.add(item.getName());
			    }
			}
			map.put("fieldList", fieldList);
			map.put("fileList", fileList);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	} 

	@SuppressWarnings("unchecked")
	public static boolean checkUpload(HttpServletRequest request,Map<String, Object> wrapper,Properties properties) {
		try {
			if (ServletFileUpload.isMultipartContent(request)) {
				Map<String,Object> ls = getFormData(request);
				if(checkSuffix((List<String>)ls.get("fileList"),properties)){
					ClientLogger.addAttackLogs(request,Constants.SYS_FUNCTION_UPLOAD);
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
